import React, { Component } from 'react';
import { connect } from 'dva';
import { Link, routerRedux } from 'dva/router';
import {  Flex, Icon,WingBlank, SwipeAction ,Toast,Popup,NavBar,Accordion,List,Popover,Checkbox, Modal,Button} from 'antd-mobile';
import MyScroll from '../../components/MyScroll/MyScroll';
import NavTopBar from '../../components/NavTopBar/NavTopBar';
import NoLazyImg from "../../components/NoLazyImg/NoLazyImg";
import {collectionList} from "./collectionList.less";
import buyCartTwo from "../../assets/svg/buyCartTwo.svg";
import sanjiaoup from "../../assets/svg/sanjiaoup.svg";
import sanjiaod from "../../assets/svg/sanjiaod.svg";
import collect from "../../assets/svg/collect.svg";
import goodsGuoXueKun from "../../assets/svg/goodsGuoXueKun.svg";

const Item = Popover.Item;
const CheckboxItem = Checkbox.CheckboxItem;
const AgreeItem = Checkbox.AgreeItem;
class CollectionList extends Component {
    constructor(props) {
        super(props);
        this.state = {
            favotitesGoodsCommodityList:[],
            favotitesGoodsStoreList:[],
            isShow:true,
            visible: false,
            selected: '',
            allVisible:false,
            isWhich:this.props.match.params.isStore,
            isClass:'',
            showType: 0,
            selectType: 0,
            editStatus:true,
            isChecked:false,

            checkedList: [],
            showAllText: '全部商品',
            showClassText: '我的分类'
        };
        this.gcid='';
        this.isCheck=[]
        this.isCheckTwo=[]
       // console.log(this.gcid)
    }
    checkAll=(e)=>{
        // if (e.target.checked == false) {
        //     this.setState({isChecked:false})
        // } else if (e.target.checked == true) {
        //     this.setState({isChecked:true})
        // }

        this.setState({isChecked: e.target.checked, checkedList: []})
    }
    onSelect = (opt) => {
        // console.log(opt.props.value,"asd", opt);
        this.setState({
            visible: false,
            selected: opt.props.value,
            isClass: 1,
            showType: opt.props.value != 'scan' ? opt.props.value == 'special' ? 2 : 3 : 1,
            showAllText:  opt.props.value != 'scan' ? opt.props.value == 'special' ? '失效商品' : '降价商品' : '全部商品',
        });

        this.gcid = `${opt.props.value}`
        console.log(opt.key);
        this.props.dispatch({type: "collectionList/CollectionListEFF", obj: {pageno: 1, type:this.props.match.params.isStore,goodsStatus:opt.key}})
        // 利用opt.props.value != 'scan' ? opt.props.value == 'special' ? 1 : 2 : 0,来识别是全部商品、失效商品还是降价商品。。。。。。。。。。。。。。
        // this.props.dispatch({type: "collectionList/CollectionListEFF", obj: {pageno: 1, type:this.props.match.params.isStore}})

    };
    onChange = (val, n) => {
        if(this.isCheck.indexOf(val)!=-1){
            var index = this.isCheck.indexOf(val);
            if (index != -1) {
                this.isCheck.splice(index, 1);
            }
        }else{
            this.isCheck.push(val)
            //console.log(this.isCheck,'1111111')
        }
    }
    onChangeTwo=(e, val, n)=>{
        // e.stopPropagation();
        // e.nativeEvent.stopImmediatePropagation();

        var index = this.state.checkedList.indexOf(val);
        console.log(val, n, index, "onChangeTwo 事件。。。");

        if(index != -1){
            console.log(index, "uanbu....", this.state.checkedList);
            this.setState({checkedList: this.state.checkedList.filter(v => v != val)})
            // this.isCheckTwo.splice(index, 1);
        }else{
            this.setState({checkedList: [val, ...this.state.checkedList]})
            // this.isCheckTwo.push(val)
            //console.log(this.isCheck,'22222')
        }

        // if (this.state.checkedList.inclues(val)) this.setState({checkedList: this.state.checkedList.filter(v => v != val)})
        // else this.setState({checkedList: [val, ...this.state.checkedList]})

    }
    delBySelected = list => {
        var data = [];
        console.log(this.state.checkedList.join(','), list, '删除商品。。。')

        if (this.state.isChecked) list.forEach(v => data.push(v.id))

        console.warn(data, 'data数据。。。');
        this.props.dispatch({ type: 'collectionList/CancelGoodsEFF',obj:{ goodsId: this.state.isChecked ? data.join(',') : this.state.checkedList.join(','), type: 1}}).then((r)=>{
            if(r.code==200 && this.state.isClass!=3){
                Toast.success(r.msg,1.5,()=>{
                    // location.reload();
                    this.props.dispatch({type: "collectionList/CollectionListEFF", obj: {pageno: 1, type: 1}})
                })
            }else{
                this.props.dispatch({ type: 'collectionList/classGoodsEFF',obj:{gcId: this.gcid}})
                this.setState({
                    editStatus:true
                });
            }
         })
    }
    delBySelectedTwo = list =>{
        console.log(this.state.checkedList.join(','), '删除店铺。。。')
        if (this.state.isChecked) list.forEach(v => data.push(v.id))

        this.props.dispatch({ type: 'collectionList/CancelGoodsEFF',obj:{goodsId: this.state.isChecked ? data.join(',') : this.state.checkedList.join(','), type: 2}}).then((r)=>{
            if(r.code==200 ){
                Toast.success(r.msg,1.5,()=>{
                    this.props.dispatch({type: "collectionList/CollectionListEFF", obj: {pageno: 1, type: 2}})
                    this.setState({editStatus:true});
                })
            }
        })
    }
    onAllSelect = (opts) => {
        console.log(opts.props,opts.props.value, opts, 'opts.......触发的时间')
        this.setState({
            allVisible: false,
            isClass:3,
            showClassText: opts.props.name
        });
        this.gcid=opts.props.value;
       // console.log(this.gcid)
        this.props.dispatch({ type: 'collectionList/classGoodsEFF', obj:{gcId: opts.props.value}})
    };
    handleVisibleChange = (visible) => {
        this.setState({
            visible,
            selectType: 0,
        });
    };
    allVisibleChange = (visible) => {
        this.setState({
            allVisible: visible,
            selectType: 1,
        });
    };

    componentDidMount() {
        this.props.dispatch({type: "collectionList/CollectionListEFF", obj: {pageno: 1, type:this.props.match.params.isStore}})
        this.props.dispatch({type: "collectionList/classFavEFF"})

    }

    onClick=(e)=>{
        e.target.parentNode.parentNode.parentNode.nextSibling.style.display = "";
    }
    change=(e)=>{
        this.setState({
            editStatus:!e
        });
    }
    // checkOne=(e)=>{
    //     this.setState({
    //         checked:true
    //     });
    //     this.state.isCheck
    // }
    render() {
        const {favotitesGoodsCommodityList={},favotitesGoodsStoreList={},checks,goods = []} = this.props.collectionList;
        const {list=[]}=favotitesGoodsCommodityList;
        const {storelist=[]}=favotitesGoodsStoreList;
        const {isWhich} = this.state;
       //  console.log(this.props.collectionList)
        console.log(isWhich==2&&storelist=="")
        console.log(isWhich==1&&list=="")
        console.log(isWhich==1&&list==""||isWhich==2&&storelist=="")
       // console.log(this.state.editStatus,'111', !this.state.editStatus ? {transform: 'translate(-1.3rem)'} : {})
        return (
            <Flex  direction="column" className={collectionList}>
                <NavBar
                    style={{ height: '.8rem', width: "100%", borderBottom: "1px solid #999999", backgroundColor: "#fff", color: "#333"}}
                    mode="dark"
                    icon={<Icon type="left" style={{width:".5rem",height:".5rem"}}/>}
                    onLeftClick={() => {
                        this.props.dispatch(routerRedux.goBack());
                    }}
                    rightContent={[<div
                            onClick={() => {
                                this.change(this.state.editStatus)
                                    // .props.dispatch({ type: 'collectionList/changeEditStatus' });
                               // console.log(editStatus)
                            }}
                            style={{ padding: '0.15rem 0.2rem', color:"#999" }}
                            key="1"
                        >{ isWhich==1&&list==""||isWhich==2&&storelist==""? "":this.state.editStatus == true ? '编辑' : '完成'}
                        </div>
                    ]}
                >

                    <span className="nav_title" style={ this.state.isWhich == 1 ? {borderBottom:"3px solid #ff0036", color: "#ff0036", marginRight: ".7rem"} : {marginRight: ".7rem"}} onClick={(e)=>{
                        this.setState({isShow:true, isWhich:1});
                        this.props.dispatch(routerRedux.replace(`/collectionList/1`))
                        this.props.dispatch({type: "collectionList/CollectionListEFF", obj: {pageno: 1, type: 1}});
                        // e.target.style.borderBottom="3px solid #ff0036";
                        // e.target.nextSibling.style.border="";
                    }}>商品</span>
                    <span className="nav_title"  style={ this.state.isWhich == 2 ? {borderBottom:"3px solid #ff0036", color: "#ff0036"} : {}} onClick={(e)=>{
                        this.setState({isShow:false,isWhich:2});
                        this.props.dispatch(routerRedux.replace(`/collectionList/2`))
                        this.props.dispatch({type: "collectionList/CollectionListEFF", obj: {pageno: 1, type: 2}});
                        // e.target.style.borderBottom="3px solid #ff0036";
                        // e.target.previousSibling.style.border="";
                    }}>店铺</span>
                </NavBar>
                {this.state.isShow==true && this.state.isWhich==1?<Flex className="fenlei"  justify="between">
                    <Popover
                        overlayClassName="fortest"
                        overlayStyle={{ color: 'currentColor' }}
                        visible={this.state.visible}
                        placement="bottom"
                        overlay={[
                            (<Item key="1" value="scan"  data-seed="logId">全部商品</Item>),
                            (<Item key="2" value="special"  style={{ whiteSpace: 'nowrap' }}>失效商品</Item>),
                            (<Item key="3" value="button ct" >
                                <span style={{ marginRight: 5 }}>降价商品</span>
                            </Item>),
                        ]}
                        align={{
                            overflow: { adjustY: 0, adjustX: 0 },
                            offset: [-10, 0],
                        }}
                        onVisibleChange={this.handleVisibleChange}
                        onSelect={this.onSelect}
                    >
                        <Flex justify="center" style={this.state.selectType == 0 ? {padding:".2rem 0",width:"50%",fontSize:".3rem",color:"#ff0036"} : {padding:".2rem 0",width:"50%",fontSize:".3rem"}}>
                            {this.state.showAllText}
                            <Icon style={{width:'.2rem',height:'.2rem',marginLeft:'.1rem'}} type={this.state.visible?sanjiaod.id:sanjiaoup.id}/>
                        </Flex>
                    </Popover>

                    <Popover
                        overlayClassName="fortest"
                        overlayStyle={{ color: 'currentColor',left:'0', zIndex: '11' }}
                        visible={this.state.allVisible}
                        placement="bottom"
                        overlay={[
                            (checks && checks!='') ? checks.map((v, i,a) => {
                                return (
                                    <Item style={{textAlign: 'center'}} key={ i + 4 } name={v.name} value={v.id}>{v.name}</Item>
                                )
                            }) : ''
                        ] }
                        align={{
                            overflow: { adjustY: 0, adjustX: 0 },
                            offset: [-10, 0],
                        }}
                        onVisibleChange={this.allVisibleChange}
                        onSelect={this.onAllSelect}
                    >
                        <div style={this.state.selectType ? {padding:".2rem 0",width:"50%",textAlign:'center',fontSize:".3rem", color: "#ff0036"} : {padding:".2rem 0",width:"50%",textAlign:'center',fontSize:".3rem"}}>
                            {this.state.showClassText}
                            <Icon style={{width:'.2rem',height:'.2rem',marginLeft:'.1rem'}} type={this.state.allVisible?sanjiaod.id:sanjiaoup.id}/>
                        </div>

                    </Popover>
                </Flex>:""}


                <MyScroll style={{position: 'absolute', top: this.state.isWhich == 1 ? '2rem' : '1rem', bottom: this.state.editStatus ? '0rem' : '1rem'}}>
                    {
                        (this.state.isWhich == 1 ? this.state.isClass == 3 ? goods : list : storelist).map((value,i)=>{
                            // console.warn(value, 'value...数据。。。');
                            if(this.state.isShow==true && this.state.isWhich==1) {
                                if(this.state.isClass== 3){
                                    goods && goods!=''? goods.map((value,i)=>{
                                        return <div style={{position:"relative"}} key={i}>
                                            <SwipeAction  style={{backgroundColor: 'gray', width: "100%"}} autoClose
                                                          right={[
                                                              {
                                                                  text: '取消收藏',
                                                                  onPress: () => {
                                                                      this.props.dispatch({type:"collectionList/favgoodsEFF",obj:{favType:1,goodsId:value.id}}).then((r)=>{
                                                                          if(r.code==200){
                                                                              Toast.success(r.msg,1.5,()=>{
                                                                                  this.props.dispatch({ type: 'collectionList/classGoodsEFF',obj:{gcId:this.gcid}})
                                                                              })
                                                                          }else{
                                                                              Toast.fail(r.msg, 1.5);
                                                                          }
                                                                      })
                                                                  },
                                                                  style: {backgroundColor: '#ff0036', color: 'white'},
                                                              },
                                                          ]} >
                                                <div style={{backgroundColor: "#fff", borderBottom: "1px solid #e5e5e5",position:"relative"}}>
                                                    <Flex style={{padding: ".3rem .2rem"}}>
                                                        { this.state.editStatus == false?<CheckboxItem key={i} checked={this.state.isChecked} onChange={() => this.onChange(value.id, 1)} /> : ""}

                                                        <NoLazyImg src={value.image}
                                                                   style={{width:"1.3rem",height:"1.3rem",borderRadius:"100%"}} onClick={()=>{
                                                            this.props.dispatch(routerRedux.push({
                                                                pathname: `/goodsDetail/${value.specId
                                                                    }`,
                                                            }));
                                                        }} />
                                                        <div style={{marginLeft: ".3rem"}}>
                                                            <p className="name">{value.name}</p>
                                                            <Flex justify="between">
                                                            <span style={{
                                                                color: "#ff0036",
                                                                fontSize: ".35rem"
                                                            }}>¥{value.storePrice}</span>
                                                            { this.state.editStatus == false ? "" : <Icon type="ellipsis" style={{color: "#999"}} onClick={this.onClick}/>}

                                                                {/* { this.state.editStatus == false?<CheckboxItem key={i} checked={this.state.isChecked} onChange={() => this.onChange(value.id)} />: <Icon type="ellipsis" style={{color: "#999"}}onClick={this.onClick}/>} */}
                                                            </Flex>
                                                        </div>
                                                    </Flex>

                                                    <Flex justify="around" className="modal"  style={{display:"none"}} onClick={(e)=>{
                                                        document.querySelectorAll(".modal")[i].style.display="none";
                                                    }}>
                                                        <div onClick={()=>{
                                                            this.props.dispatch({type:"collectionList/favgoodsEFF",obj:{favType:1,goodsId:value.id}}).then((r)=>{
                                                                if(r.code==200){
                                                                    Toast.success(r.msg,1.5,()=>{
                                                                        this.props.dispatch({type: "collectionList/CollectionListEFF", obj: {pageno: 1, type: 1}})
                                                                    })
                                                                }else{
                                                                    Toast.fail(r.msg, 1.5);
                                                                }
                                                            })
                                                        }} style={{textAlign:"center"}}>
                                                            <Icon type={collect.id} style={{width:"1rem",height:"1rem"}}></Icon>
                                                            <p>取消收藏</p>
                                                        </div>
                                                        <div style={{textAlign:"center"}} onClick={()=>{console.log(111)
                                                            this.props.dispatch({ type:'collectionList/addCartOrBuyEFF', obj: { saveType:0,goodsId: value.id, specId: value.specId } });}}>
                                                            <Icon type={buyCartTwo.id} style={{width:"1rem",height:"1rem"}}></Icon>
                                                            <p>加入购物车</p>
                                                        </div>
                                                        <div onClick={() => {
                                                                this.props.dispatch(routerRedux.push({pathname: `/goodsearch/keywordSearch?keyword=${value.name}`}))
                                                            }} style={{textAlign:"center"}}>
                                                            <Icon type={goodsGuoXueKun.id} style={{width:"1rem",height:"1rem"}}></Icon>
                                                            <p>相似商品</p>
                                                        </div>
                                                    </Flex>
                                                </div>
                                            </SwipeAction>
                                        </div>}):''
                                }
                                return <div style={{position:"relative"}} key={i}>

                                    <SwipeAction  style={{backgroundColor: 'gray', width: "100%"}} autoClose
                                                  right={[
                                                      {
                                                          text: '加入购物车',
                                                          onPress: () => {
                                                              this.props.dispatch({ type:'collectionList/addCartOrBuyEFF', obj: { saveType:0,goodsId: value.id, specId: value.specId } });
                                                          },
                                                          style: {backgroundColor: '#ff9402', color: 'white'},
                                                      },
                                                      {
                                                          text: '取消收藏',
                                                          onPress: () => {
                                                              this.props.dispatch({type:"collectionList/favgoodsEFF",obj:{favType:1,goodsId:value.id}}).then((r)=>{
                                                                  if(r.code==200){
                                                                      Toast.success(r.msg,1.5,()=>{
                                                                          console.log('取消收藏中！！！')
                                                                          if(this.state.isClass==3){
                                                                              this.props.dispatch({ type: 'collectionList/classGoodsEFF',obj:{gcId:this.gcid}})

                                                                          }else{
                                                                              this.props.dispatch({type: "collectionList/CollectionListEFF", obj: {pageno: 1, type: 1}})
                                                                          }

                                                                      })
                                                                  }else{
                                                                      Toast.fail(r.msg, 1.5);
                                                                  }
                                                              })
                                                          },
                                                          style: {backgroundColor: '#ff0036', color: 'white'},
                                                      },
                                                  ]} >
                                        <div style={{backgroundColor: "#fff", borderBottom: "1px solid #e5e5e5",position:"relative"}}>
                                            <Flex style={{padding: ".3rem .2rem"}}>
                                                { this.state.editStatus == false ? <CheckboxItem style={{paddingLeft: '0rem'}} key={i} checked={this.state.isChecked || this.state.checkedList.includes(value.id)} onChange={e => this.onChangeTwo(e, value.id, 2)}/>:''}

                                                <NoLazyImg src={value.image}
                                                           style={{width: "1.5rem",height:"1.5rem"}}  onClick={()=>{
                                                    this.props.dispatch(routerRedux.push({pathname: `/goodsDetail/${value.specId}`}));
                                                }}/>
                                                <div style={{marginLeft: ".3rem", width: this.state.editStatus == false ? '65%' : '70%'}}>
                                                    <p className="name">{value.name}</p>
                                                    <Flex justify="between">
                                                            <span style={{
                                                                color: "#ff0036",
                                                                fontSize: ".35rem"
                                                            }}>¥{value.storePrice}</span>
                                                        {/*{ this.state.editStatus == false ? "" : <Icon type="ellipsis" style={{color: "#999"}}onClick={this.onClick}/>}*/}


                                                    </Flex>
                                                </div>
                                            </Flex>

                                            <Flex justify="around" className="modal"  style={{display:"none"}} onClick={(e)=>{
                                                document.querySelectorAll(".modal")[i].style.display="none";
                                            }}>
                                                <div style={{textAlign:"center"}} onClick={()=>{
                                                    this.props.dispatch({type:"collectionList/favgoodsEFF",obj:{favType:1,goodsId:value.id}}).then((r)=>{
                                                        if(r.code==200){
                                                            Toast.success(r.msg,1.5,()=>{
                                                                this.props.dispatch({type: "collectionList/CollectionListEFF", obj: {pageno: 1, type: 1}})
                                                            })
                                                        }else{
                                                            Toast.fail(r.msg, 1.5);
                                                        }
                                                    })
                                                }}>
                                                    <Icon type={collect.id} style={{width:"1rem",height:"1rem"}}></Icon>
                                                    <p>取消收藏</p>
                                                </div>
                                                <div style={{textAlign:"center"}} onClick={()=>{ this.props.dispatch({ type:'collectionList/addCartOrBuyEFF', obj: { saveType:0,goodsId: value.id, specId: value.specId } }).then(result=>{console.log(result)});console.log(111)}}>
                                                    <Icon type={buyCartTwo.id} style={{width:"1rem",height:"1rem"}}></Icon>
                                                    <p>加入购物车</p>
                                                </div>
                                                <div  onClick={() => {
                                                    this.props.dispatch(routerRedux.push({pathname: `/goodsearch/keywordSearch?keyword=${value.name}`}))
                                                }} style={{textAlign:"center"}}>
                                                    <Icon type={goodsGuoXueKun.id} style={{width:"1rem",height:"1rem"}}></Icon>
                                                    <p>相似商品</p>
                                                </div>
                                            </Flex>
                                        </div>
                                    </SwipeAction>

                                    {/*{list.length==0?<div style={{color:"#999"}}>*/}
                                    {/*<Icon type={noMoresvg.id}></Icon>*/}
                                    {/*<p>您还没收藏任何商品</p>*/}
                                    {/*<p>到 <Link to="/" style={{color:"#ff0036"}}>首页</Link>逛逛吧</p>*/}
                                    {/*</div>:""}*/}
                                </div>

                            }else if(this.state.isWhich==2){
                                return <div style={{width:"100%"}}  key={i}>
                                    <SwipeAction style={{ backgroundColor: 'gray',width:"100%" }} autoClose right={[
                                        {
                                            text: '取消收藏',
                                            onPress: () => {
                                                this.props.dispatch({type:"collectionList/favgoodsEFF",obj:{favType:2,id:value.storeId}}).then((r)=>{
                                                    if(r.code==200){
                                                        Toast.success(r.msg,1.5,()=>{
                                                            location.reload();
                                                        })
                                                    }else{
                                                        Toast.fail(r.msg, 1.5);
                                                    }
                                                })
                                            },
                                            style: { backgroundColor: '#ff0036', color: 'white' },
                                        },
                                    ]} onOpen={() => console.log('global open')} onClose={() => console.log('global close')}>
                                        <div  style={{backgroundColor:"#fff",borderBottom:"1px solid #e5e5e5"}}>
                                            <WingBlank >
                                                <Flex justify="between" style={{padding:".3rem 0"}}>
                                                    { this.state.editStatus == false ?
                                                        <CheckboxItem
                                                            style={{paddingLeft: '0rem', width: '.7rem'}}
                                                            key={i}
                                                            checked={this.state.isChecked || this.state.checkedList.includes(value.storeId)}
                                                            onChange={e => this.onChangeTwo(e, value.storeId, 2)}
                                                        /> : ''
                                                    }

                                                    <Flex style={!this.state.editStatus ? {transform: 'translate(-1.3rem)'} : {}}
                                                          onClick={()=> {
                                                                value.storeId!=0?this.props.dispatch(routerRedux.push({
                                                                    pathname: `/storesShow/${value.storeId}`
                                                                })):''
                                                    }}>

                                                        <NoLazyImg src={value.storeImg} style={{width:"1.3rem",height:"1.3rem",borderRadius:"100%"}} alt=""/>
                                                        <p className="Name">{value.storeName}</p>
                                                    </Flex>
                                                    <div style={{color:"#666",fontSize:"0.3rem"}}>
                                                        <p>上新</p>
                                                        <p style={{textAlign:"center"}}>{value.num}</p>
                                                    </div>

                                                </Flex>
                                            </WingBlank>
                                        </div>
                                    </SwipeAction>
                                    {/*{storelist.length==0?<div style={{color:"#999"}}>*/}
                                    {/*<Icon type={noMoresvg.id}></Icon>*/}
                                    {/*<p>您还没收藏任何店铺</p>*/}
                                    {/*<p>到 <Link to="/" style={{color:"#ff0036"}}>首页</Link>逛逛吧</p>*/}
                                    {/*</div>:""}*/}
                                </div>
                            }
                        })
                    }
                </MyScroll>


                <div style={{width:'100%',position:'fixed', backgroundColor: '#fff', bottom:'0',display:this.state.editStatus?'none':'block'}}>
                    <Flex justify="between">
                        <div>
                            <AgreeItem
                                // checked={ isAllCheck==1 ? true : false }
                                onChange={(e) => this.checkAll(e)}
                            >
                                全选
                            </AgreeItem>
                        </div>
                        <Button onClick={this.state.isWhich == 2 ? () => this.delBySelectedTwo(storelist) : () => this.delBySelected(this.state.isClass == 3 ? goods : list)} style={{background:'#FE0036',borderColor:'#FE0036',width:"30%",borderRadius:"0",color:'#fff'}}> 删除</Button>
                    </Flex>

                </div>
            </Flex>
        );
    }
}


export default connect(({ collectionList }) => ({ collectionList }))(CollectionList);
